package com.xb.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xb.model.system.SysRole;
import com.xb.model.system.SysUserRole;
import com.xb.model.vo.AssginRoleVo;
import com.xb.model.vo.SysRoleQueryVo;
import com.xb.system.mapper.SysRoleMapper;
import com.xb.system.mapper.SysUserRoleMapper;
import com.xb.system.service.SysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;
    //分页查询
    @Override
    public IPage<SysRole> selectPage(Page<SysRole> pageParam, SysRoleQueryVo roleQueryVo) {

        IPage<SysRole> pageModel = baseMapper.selectPage(pageParam, roleQueryVo);

        return pageModel;

    }

    //获取用户角色
    @Override
    public Map<String, Object> getRolesByUserId(Long userId) {
        //获取所有的角色信息
        List<SysRole> roles = sysRoleMapper.selectList(null);
        //获取用户的角色信息
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(queryWrapper);
        //获取用户角色id
        List<Long> userRoleIds = new ArrayList<>();
        for (SysUserRole sysUserRole : userRoles) {
            userRoleIds.add(sysUserRole.getRoleId());
        }
        //创建返回的Map
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("allRoles",roles);
        returnMap.put("userRoleIds",userRoleIds);
        return returnMap;
    }

    //角色分配
    @Override
    @Transactional//开启事务
    public void doAssign(AssginRoleVo assginRoleVo) {
        //删除用户原有的角色信息
        Long userId = assginRoleVo.getUserId();
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        sysUserRoleMapper.delete(queryWrapper);
        //添加用户新的角色信息
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        for (Long roleId : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }
}
